package com.ddx.service.impl;

import com.ddx.common.enums.ErrorCode;
import com.ddx.common.exception.BusinessException;
import com.ddx.common.exception.ResultModel;
import com.ddx.common.redis.RedisService;
import com.ddx.common.util.DataUtil;
import com.ddx.common.util.FastDFSClient;
import com.ddx.convert.ProductConverter;
import com.ddx.dao.*;
import com.ddx.dto.BatchEditProduct;
import com.ddx.dto.ShoppingProductVo;
import com.ddx.pojo.*;
import com.ddx.service.AdvertService;
import com.ddx.service.IShoppingOrderService;
import com.ddx.service.IShoppingProductService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author dudianbo
 * @ClassName: ${CLASSNAME}
 * @Description: ${DESCRIPTION}
 * @date 2018/9/5
 */
@Service
public class ShoppingProductServiceImpl implements IShoppingProductService {

    private static Logger logger = LoggerFactory.getLogger(ShoppingProductServiceImpl.class);

    @Autowired
    ShoppingCatalogMapper shoppingCatalogMapper;

    @Autowired
    ShoppingProductMapper shoppingProductMapper;

    @Autowired
    ShoppingStoreMapper shoppingStoreMapper;

    @Autowired
    ShoppingSpecMapper shoppingSpecMapper;

    @Autowired
    ShoppingAttributeMapper shoppingAttributeMapper;

    @Value("${image_address}")
    String imageAddress;

    @Autowired
    RedisService redisService;

    @Autowired
    IShoppingOrderService orderService;

    @Autowired
    AdvertService advertService;

    /**
     * 商品信息
     * @return
     */
    @Override
    public List<ShoppingProductVo> productInfo(ShoppingProductVo shoppingProductVo) {
        logger.info("查询商品信息入参shoppingProductVo={}",shoppingProductVo);
        List<ShoppingProductVo> voList=new ArrayList<>();
        List<ShoppingProduct> list=shoppingProductMapper.selectByRecord(shoppingProductVo);
        for(ShoppingProduct shoppingProduct:list){
            ShoppingProductVo vo=new ShoppingProductVo();
            BeanUtils.copyProperties(shoppingProduct,vo);
            vo.setPicture(imageAddress+shoppingProduct.getPicture());
            vo.setGold(shoppingProduct.getMemberPrice().multiply(shoppingProduct.getFeeRate()).setScale(2,BigDecimal.ROUND_DOWN));
            String fee=shoppingProduct.getFeeRate()==null?"0":shoppingProduct.getFeeRate().movePointRight(2)+"%";
            vo.setFeeRateDes(fee);
            voList.add(vo);
        }
        return voList;
    }
    /**
     * 商品明细
     * @param productId
     * @return
     */
    @Override
    public ShoppingProductVo productDetail(int productId) {
        logger.info("查询商品明细入参productId={}", productId);
        if (productId == 0) {
            throw new BusinessException(ErrorCode.BUSSINESS_ERROR_203);
        }
        ShoppingProduct shoppingProduct = shoppingProductMapper.selectByPrimaryKey(productId);
        ShoppingProductVo shoppingProductVo=new ShoppingProductVo();
        BeanUtils.copyProperties(shoppingProduct,shoppingProductVo);
        if(StringUtils.isNotBlank(shoppingProduct.getImages())) {
            List<String> list=new ArrayList<>();
            String[] s=shoppingProduct.getImages().split(",");
            for(String string:s){
                list.add(imageAddress+string);
            }
            shoppingProductVo.setPictures(list);
        }
        //查询商品店铺信息
        ShoppingStore shoppingStore=shoppingStoreMapper.selectByPrimaryKey(Integer.parseInt(shoppingProduct.getShopId()));
        shoppingProductVo.setShoppingStore(shoppingStore);
        shoppingProductVo.setGold(shoppingProduct.getMemberPrice().multiply(shoppingProduct.getFeeRate()).setScale(2, BigDecimal.ROUND_DOWN));
        shoppingProductVo.setPicture(imageAddress+shoppingProduct.getPicture());

        /*Integer sumSpecStock=shoppingSpecMapper.sumSpecStock(productId);
        sumSpecStock=sumSpecStock==null?0:sumSpecStock;
        shoppingProductVo.setStock(sumSpecStock);*/
        //更改浏览次数
        ShoppingProduct record=new ShoppingProduct();
        record.setId(productId);
        shoppingProductMapper.updateHitById(record);
        return shoppingProductVo;
    }

    /**
     * 修改库存和已售
     * @param detail
     * @return
     */
    @Override
    public void updateStockAndYishou(ShoppingOrderDetail detail){
        //修改库存
//        ShoppingSpec record=new ShoppingSpec();
//        record.setSpecStock(detail.getNumber().toString());
//        record.setId(Integer.parseInt(detail.getSpecId()));
//        shoppingSpecMapper.updateStockByRecord(record);
        //修改已售
        ShoppingProduct shoppingProduct=new ShoppingProduct();
        shoppingProduct.setId(Integer.parseInt(detail.getProductId()));
        shoppingProduct.setSellcount(detail.getNumber());
        shoppingProductMapper.updateSellcountById(shoppingProduct);
    }

    @Override
    public ResultModel addProduct(int userId, ShoppingProductVo productVo) throws Exception{
        ShoppingStore shoppingStore = shoppingStoreMapper.selectByUserId(userId);
        productVo.setShopId(shoppingStore.getId().toString());
        ShoppingProduct product = new ProductConverter().convert(productVo);
        if(StringUtils.isNotBlank(productVo.getPicture())) {
            String[] s = productVo.getPicture().split(",");
            if (s.length > 1) {
                byte[] b = DataUtil.GenerateImage(s[1]);
                String url = FastDFSClient.uploadFileByByteAndGroup(b, "group1");
                product.setPicture(url);
            }
        }
        if(StringUtils.isNotBlank(productVo.getProductHtml())) {
            String[] s = productVo.getProductHtml().split(",");
            if (s.length > 1) {
                byte[] b = DataUtil.GenerateImage(s[1]);
                String url = FastDFSClient.uploadFileByByteAndGroup(b, "group1");
                product.setProductHtml(url);
            }
        }
        shoppingProductMapper.insert(product);
        advertService.insertByProduct(product, userId);
        return ResultModel.getSuccessInstance();
    }

    @Override
    public ResultModel editProduct(int userId, ShoppingProductVo productVo) {
        ShoppingStore shoppingStore = shoppingStoreMapper.selectByUserId(userId);
        productVo.setShopId(shoppingStore.getId().toString());
        shoppingProductMapper.updateByPrimaryKeySelective(new ProductConverter().convert(productVo));
        return ResultModel.getSuccessInstance();
    }

    @Override
    public Map<String, Object> getProductMap(int storeId, int index, int size, int status) {
        Map<String, Object> returnMap = new HashMap<>();
        int count = shoppingProductMapper.countByParam(storeId, status);
        List<ShoppingProduct> shoppingProductList = shoppingProductMapper.selectByParam(storeId, status, index * size, size);
        List<Map<String, Object>> productList = new ArrayList<>();
        if (!CollectionUtils.isEmpty(shoppingProductList)) {
            List<Integer> productIdList = shoppingProductList.stream().map(product -> product.getId()).collect(Collectors.toList());
            Map<Integer, BigDecimal> productSaleAmountMap = orderService.getProductSaleAmount(productIdList);
            for (ShoppingProduct product : shoppingProductList) {
                Map<String, Object> map = new HashMap<>();
                map.put("productId", product.getId());
                map.put("picture", imageAddress+product.getPicture());
                map.put("title", product.getTitle());
                map.put("nowPrice", product.getNowPrice());
                map.put("stock", product.getStock());
                map.put("sellCount", product.getSellcount());
                map.put("createTime", product.getCreateTime());
                map.put("saleAmount", productSaleAmountMap.get(product.getId()) != null ? productSaleAmountMap.get(product.getId()) : 0);
                map.put("status", product.getStatus());
                productList.add(map);
            }
        }
        returnMap.put("count", count);
        returnMap.put("productList", productList);
        return returnMap;
    }

    @Override
    public ResultModel getProductInfo(int userId, int index, int size, int status) {
        ShoppingStore shoppingStore = shoppingStoreMapper.selectByUserId(userId);
        Map<String, Object> productMap = getProductMap(shoppingStore.getId(), index, size, status);
        ResultModel resultModel = ResultModel.getSuccessInstance();
        resultModel.setData(productMap);
        return resultModel;
    }

    /**
     * 批量上下架
     *
     * @return
     */
    @Override
    public ResultModel batchEdit(BatchEditProduct batchEditProduct) {
        shoppingProductMapper.batchEdit(batchEditProduct.getProductIdList(), batchEditProduct.getStatus());
        return ResultModel.getSuccessInstance();
    }
    
    /**
     * 出售中,已下架 的商品集合list【根据status状态区分商品状态 0 正常 1下架】
     */
	@Override
	public Map<String, Object> sell(ShoppingProductVo shoppingProductVo) throws Exception{
		if(StringUtils.isBlank(shoppingProductVo.getShopId())){
			throw new BusinessException(ErrorCode.BUSSINESS_ERROR_201,"shopId为空");
		}
		if(shoppingProductVo.getStatus()==null){
			throw new BusinessException(ErrorCode.BUSSINESS_ERROR_201,"status为空");
		}
		if(shoppingProductVo.getPageNo()==null){
			throw new BusinessException(ErrorCode.BUSSINESS_ERROR_201,"pageNo为空");
		}
		if(shoppingProductVo.getPageSize()==null){
			throw new BusinessException(ErrorCode.BUSSINESS_ERROR_201,"pageSize为空");
		}
		return getProductMap(Integer.parseInt(shoppingProductVo.getShopId()),shoppingProductVo.getPageNo(),shoppingProductVo.getPageSize(),shoppingProductVo.getStatus());
	}
	
	/**
	 * 根据视频详情返回结果提供的商品id-跳转商品详情页
	 */
	@Override
	public Map<String, Object> detailById(ShoppingProductVo shoppingProductVo) throws Exception {
		Map<String, Object> map = new HashMap<String,Object>();
		logger.info("查询商品明细入参productId={}", shoppingProductVo.getId());
        if (shoppingProductVo.getId()==null || shoppingProductVo.getId() == 0) {
            throw new BusinessException(ErrorCode.BUSSINESS_ERROR_201,"商品 id为空");
        }
        ShoppingProduct shoppingProduct = shoppingProductMapper.selectByPrimaryKey(shoppingProductVo.getId());
        BeanUtils.copyProperties(shoppingProduct,shoppingProductVo);
        if(StringUtils.isNotBlank(shoppingProduct.getImages())) {
            List<String> list=new ArrayList<>();
            String[] s=shoppingProduct.getImages().split(",");
            for(String string:s){
                list.add(imageAddress+string);
            }
            shoppingProductVo.setPictures(list);
        }
        //查询商品店铺信息
        ShoppingStore shoppingStore=shoppingStoreMapper.selectByPrimaryKey(Integer.parseInt(shoppingProduct.getShopId()));
        shoppingProductVo.setShoppingStore(shoppingStore);
        shoppingProductVo.setPicture(imageAddress+shoppingProduct.getPicture());

        //评价暂无
        
        
        map.put("shoppingProduct", shoppingProductVo);
        map.put("shoppingStore", shoppingStore);
        return map;
	}

    @Override
    public ResultModel getProductDetail(int productId) {
        ResultModel resultModel = ResultModel.getSuccessInstance();
        ShoppingProduct product = shoppingProductMapper.selectByPrimaryKey(productId);
        if(product.getPicture()!=null&&!product.getPicture().contains("http")){
            product.setPicture(imageAddress+product.getPicture());
        }
        if(product.getProductHtml()!=null&&!product.getProductHtml().contains("http")){
            product.setProductHtml(imageAddress+product.getProductHtml());
        }
        resultModel.setData(product);
        return resultModel;
    }

    @Override
    public ResultModel deleteProduct(int productId) {
        ResultModel resultModel = ResultModel.getSuccessInstance();
        shoppingProductMapper.deleteByPrimaryKey(productId);
        return resultModel;
    }
}
